package com.example.administrator.baikangxing.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.example.administrator.baikangxing.Dao.OperateData;
import com.example.administrator.baikangxing.MyApplication;
import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.adapter.HomeAdapter;
import com.example.administrator.baikangxing.adapter.SelectItemAdapter;
import com.example.administrator.baikangxing.bean.BindDevice;
import com.example.administrator.baikangxing.bean.HomeInfo;
import com.example.administrator.baikangxing.config.Constants;
import com.example.administrator.baikangxing.config.Url;
import com.example.administrator.baikangxing.utils.CommomUtil;
import com.example.administrator.baikangxing.utils.HttpUtil;
import com.example.administrator.baikangxing.utils.LogUtil;
import com.example.administrator.baikangxing.utils.ScreenUtils;
import com.example.administrator.baikangxing.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends SupportMapFragment {

    private Banner home_banner;
    private ViewPager home_vp;
    private TabLayout home_tb;
    private TextureMapView home_map;
    private AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private ImageButton home_menu;
    private LinearLayout menu_ll;
    private LinearLayout home_ll_head;
    private LinearLayout.LayoutParams lp;
    private ArrayList<String> device_list_num;
    private TextView home_tv_title;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view, savedInstanceState);
        initListerner();
    }

    public void initView(View view, Bundle savedInstanceState) {
        home_ll_head = (LinearLayout) view.findViewById(R.id.home_ll_head);
        home_tb = (TabLayout) view.findViewById(R.id.home_tb);
        menu_ll = (LinearLayout) view.findViewById(R.id.menu_ll);
        home_tv_title = (TextView) view.findViewById(R.id.home_tv_title);
        home_vp = (ViewPager) view.findViewById(R.id.home_vp);
        home_map = (TextureMapView) view.findViewById(R.id.home_map);
        home_menu = (ImageButton) view.findViewById(R.id.home_ib_menu);
        home_map.onCreate(savedInstanceState);
        aMap = null;
        if (aMap == null) {
            aMap = home_map.getMap();
        }
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setScaleControlsEnabled(true);
        home_banner = (Banner) view.findViewById(R.id.home_banner);//设置轮播图
        home_banner.setBannerStyle(BannerConfig.CENTER);
        home_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        Integer[] images = {R.drawable.banner_bg, R.drawable.banner_bg, R.drawable.banner_bg};
        home_banner.setImages(images);
        LinearLayout linearLayout = (LinearLayout) home_tb.getChildAt(0);//添加分割线
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(getContext(),
                R.drawable.layout_divider_vertical));
        linearLayout.setDividerPadding(20);
        initData();
    }

    public void initData() {
        List<Fragment> list = new ArrayList<>();//设置tablayout
        list.add(new MeterFragment());
        list.add(new FunctionFragment());
        HomeAdapter adapter = new HomeAdapter(getFragmentManager(), list);
        home_vp.setAdapter(adapter);
        home_tb.setupWithViewPager(home_vp);
        String stringData = OperateData.getStringData(getContext(), Constants.SELECT_DEVICE_NUM);
        if(stringData.equals("") || stringData == null){
            LatLng latLng = new LatLng(34.341568, 108.940174);
            setMap(latLng,"式例");
        }else {
            setData(OperateData.getStringData(getContext(), Constants.SELECT_DEVICE_NUM), OperateData.getStringData(getContext(), Constants.SELECT_DEVICE_NAME));
        }
    }

    private void setMap(LatLng latLng,String str) {
        aMap.clear();
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));//移动中心点到指定位置
        aMap.addMarker(new MarkerOptions().position(latLng).title(str));//设置标记点
    }

    private void initListerner() {
        home_banner.setOnBannerClickListener(new OnBannerClickListener() {//轮播图的点击事件
            @Override
            public void OnBannerClick(int position) {

            }
        });
        home_menu.setOnClickListener(new View.OnClickListener() {//菜单的点击事件
            @Override
            public void onClick(View view) {
                String[] values = {OperateData.getStringData(MyApplication.context, Constants.USER_NAME),"ext"};
                HttpUtil.getInstance().postString(Url.get_dev_list, new String[]{"user", "ext"}, values, new HttpUtil.CallBackPostString() {
                    @Override
                    public void onSuccess(JSONObject successString) {
                        try {
                            if(successString.getString("errorCode").equals("0")){
                                JSONArray message = successString.getJSONArray("message");
                                ArrayList<BindDevice> bindDevices = CommomUtil.parserJsonArrayToList(message, BindDevice.class);
                                if(bindDevices.size()>0 ){//存在绑定设备
                                    device_list_num = new ArrayList<String>();
                                    ArrayList<String> device_list_name =  new ArrayList<>();
                                    for (int i = 0; i < bindDevices.size(); i++) {
                                        String device = bindDevices.get(i).getDevid();
                                        String nickName = bindDevices.get(i).getNickname();
                                        device_list_num.add(device);
                                        device_list_name.add(nickName);
                                    }
                                    showDialog(device_list_name);//弹出选择dialog
                                }else {//没有绑定的设备
                                    /*没有绑定设备，暂不处理*/
                                    ToastUtil.showToast("暂无绑定设备");
                                }
                            }else {//获取失败
                                ToastUtil.showToast(successString.getString("errorinfo"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(JSONObject failString) {
                        ToastUtil.showToast(getString(R.string.error_net_hint));
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {

                    }
                });
            }
        });
    }

    private void showDialog(final ArrayList<String> device_list_name) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.dialog);
        LinearLayout linearLayoutMain = new LinearLayout(getContext());//自定义一个布局文件
        linearLayoutMain.setGravity(Gravity.CENTER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            linearLayoutMain.setBackground(getResources().getDrawable(R.drawable.drop_box));
        }
        linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT ));
        linearLayoutMain.setPadding(0,0,0,0);
        ListView listView = new ListView(getContext());
        listView.setDivider(new ColorDrawable(Color.WHITE));
        listView.setDividerHeight(1);
        //listView.setBackgroundColor(getResources().getColor(R.color.green));
        SelectItemAdapter adapter = new SelectItemAdapter(device_list_name);
        listView.setAdapter(adapter);
        linearLayoutMain.addView(listView);//往这个布局中加入listview
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        linearParams.gravity = Gravity.CENTER;
        linearParams.setMargins(0,0,0,0);
        linearParams.width = ScreenUtils.getScreenWidth(getContext())/3;
        listView.setLayoutParams(linearParams); //使设置好的布局参数应用到控件
        final AlertDialog dialog = builder.setView(linearLayoutMain).create();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.RIGHT|Gravity.TOP);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width =  ScreenUtils.getScreenWidth(MyApplication.context) / 4;// 宽度
        layoutParams.y = home_ll_head.getHeight()+getStatusBarHeight()-40;
        layoutParams.x = 10;
        window.setAttributes(layoutParams);
        dialog.show();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ToastUtil.showToast("你选择了"+device_list_name.get(i));
                OperateData.saveStringData(getContext(), Constants.SELECT_DEVICE_NUM, device_list_num.get(i));
                OperateData.saveStringData(getContext(), Constants.SELECT_DEVICE_NAME, device_list_name.get(i));
                setData(device_list_num.get(i),device_list_name.get(i));
                LogUtil.e("查看设备："+device_list_num.get(i));
                dialog.dismiss();
            }
        });
        LogUtil.e("listview的宽度为"+listView.getMeasuredWidth());
    }

    private void setData(String s, final String str) {
        HttpUtil.getInstance().postString(Url.get_dev_single, new String[]{"devid"}, new String[]{s}, new HttpUtil.CallBackPostString() {
            @Override
            public void onSuccess(JSONObject successString) {
                try {
                    String errorCode = successString.getString("errorCode");
                    if(errorCode.equals("0")){//获取数据成功
                        JSONObject message = successString.getJSONObject("message");
                        JSONObject heartRateJsonObject = message.getJSONObject("heartrate");
                        String heartRate = heartRateJsonObject.getString("heartrate");
                        JSONObject bloodOxygenJsonObject = message.getJSONObject("bloodoxygen");
                        String bloodOxygen = bloodOxygenJsonObject.getString("bloodoxygen");
                        JSONObject passometerJsonObject = message.getJSONObject("passometer");
                        String passometer = passometerJsonObject.getString("passometer");
                        JSONObject locationJsonObject = message.getJSONObject("location");
                        String lng = locationJsonObject.getString("lng");
                        String lat = locationJsonObject.getString("lat");
                        JSONObject sleepingJsonObject = message.getJSONObject("sleeping");
                        String sleepTime = sleepingJsonObject.getString("sleeptime");
                        String deepSleepTime = sleepingJsonObject.getString("deepsleeptime");
                        JSONObject bloodPresureJsonObject = message.getJSONObject("bloodPresure");
                        String lowPresure = bloodPresureJsonObject.getString("lowpresure");
                        String highPresure = bloodPresureJsonObject.getString("highpresure");
                        setMap(new LatLng(Double.parseDouble(lat),Double.parseDouble(lng)),str);
                        EventBus.getDefault().post(new HomeInfo(heartRate, bloodOxygen, passometer, lng, lat, sleepTime, deepSleepTime, lowPresure, highPresure));
                        if(str.equals("0")){
                            home_tv_title.setText("首页");
                        }else {
                            home_tv_title.setText(str+"的手表");
                        }
                    }else {
                        LogUtil.e(successString.getString("errorInfo"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(JSONObject failString) {

            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {

            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        home_map.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        home_map.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        home_map.onSaveInstanceState(bundle);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        home_map.onDestroy();
    }

    /**
     * 通过反射的方式获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
